package com.iuie.ns.datum.maker.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.iuie.ns.datum.vo.TableFieldVO;
import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.system.maker.AbstractMarkdownBatchMaker;

public class FieldWithAFormatMaker extends AbstractMarkdownBatchMaker<TableFieldVO> {

	public FieldWithAFormatMaker(String rule) {
		super(rule);
	}

	@Override
	protected TableFieldVO getObject() {
		return new TableFieldVO();
	}

	@Override
	protected void setObjectAttribute(TableFieldVO field, String value, int index) {
		switch (index) {
		case 0:
			value = StringUtils.upperCase(value);
			field.setFieldName(value);
			break;
		case 1:
			Pattern pattern = Pattern.compile("(?<=\\()[^\\)]+");
			Matcher matcher = pattern.matcher(value);
			while(matcher.find()){
				String fieldLength = matcher.group();
				field.setFieldLength(Integer.valueOf(fieldLength));
			}
			String mValue = StringUtils.upperCase(value);
			if (StringUtils.startsWith(mValue, "VARCHAR")) {
				field.setFieldType("VARCHAR");
				if (field.getFieldLength() == null) {
					field.setFieldLength(255);
				}
				break;
			}
			if (StringUtils.startsWith(mValue, "CHAR")) {
				field.setFieldType("CHAR");
				if (field.getFieldLength() == null) {
					field.setFieldLength(255);
				}
				break;
			}
			field.setFieldType(mValue);
			break;
		case 2:
			field.setAllowNull(convertValue("allowNull", value));
			break;
		case 3:
			field.setDisplay(value);
			break;
		case 4:
			field.setComment(value);
			break;
		case 5:
			field.setIsPrimaryKey(convertValue("isPrimaryKey", value));
			break;
		default:
			break;
		}
	}
	
	private String convertValue(String attribute, String value) {
		if (StringUtils.equals(value, "是") || StringUtils.equals(value, "允许") || StringUtils.equals(value, "Y")
				|| StringUtils.isBlank(value) || StringUtils.equals("1", value)) {
			return "1";
		}
		if (StringUtils.equals(value, "不是") || StringUtils.equals(value, "不允许") || StringUtils.equals(value, "禁止") 
				|| StringUtils.equalsIgnoreCase(value, "N") || StringUtils.equalsIgnoreCase("0", value)) {
			return "0";
		}
		throw new ServiceException("不支持的值，【" + attribute + "= " + value + "】");
		
	}
	
}
